package com.mymarkdown.app.websocket.handler;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.mymarkdown.app.common.ChainHandlerResult;
import com.mymarkdown.app.websocket.enums.MessageTypeEnum;
import com.mymarkdown.app.websocket.interfaces.HandlerMessage;
import com.mymarkdown.app.websocket.message.MessagePojo;

import javax.websocket.Session;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * @author zenglun
 * @date 2021/12/5 11:45 上午
 * @description: 中央处理消息器
 */
public class SelectiveMessageHandler implements HandlerMessage {
    private List<HandlerMessage> handlerMessages;

    private static SelectiveMessageHandler self;

    private SelectiveMessageHandler() {

    }

    public static SelectiveMessageHandler getSelf() {
        if (self == null) {
            synchronized (SelectiveMessageHandler.class) {
                if (self == null) {
                    self = new SelectiveMessageHandler();
                }
            }
        }
        return self;
    }

    public void setHandlerMessages(List<HandlerMessage> handlerMessages) {
        this.handlerMessages = handlerMessages;
    }

    @Override
    public ChainHandlerResult onMessage(String message, Session session) {
        if (StrUtil.isEmpty(message)) {
            return ChainHandlerResult.empty().setResult(false).setMessage("消息内容为空!");
        }
        try {
            //转换数据
            MessagePojo messagePojo = JSON.parseObject(message, MessagePojo.class);
            if (StrUtil.isEmpty(messagePojo.getMessageType())) {
                throw new NullPointerException("消息类型为空!");
            }
            Optional<ChainHandlerResult> optional = Optional.ofNullable(handlerMessages).orElseGet(ArrayList::new).stream()
                    .map(el -> {
                        MessageTypeEnum handlerType = el.getHandlerType();
                        if (StrUtil.equals(messagePojo.getMessageType(), handlerType.getMessageType())) {
                            //开始执行
                            return el.onMessage(messagePojo.getBody(), session);
                        }
                        return null;
                    }).filter(ObjectUtil::isNotNull).findAny();
            return optional.orElse(ChainHandlerResult.empty().setSkip(true).setMessage("没有找到相关处理类!").setResult(false));
        } catch (Exception e) {
            return ChainHandlerResult.empty().setResult(false).setMessage(e.getMessage()).setException(e);
        }
    }

    @Override
    public MessageTypeEnum getHandlerType() {
        return MessageTypeEnum.EMPTY;
    }
}
